package com.ym.pms.controller;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.ym.pms.service.IFileUploadService;
import com.ym.pms.utils.JSONResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: xybh
 * @Description:
 * @Date: Created in 12:29 2020/12/14
 * @Modified:
 */
@RestController
@Configuration
public class FileUploadController {

    @Autowired
    private IFileUploadService fileUploadService;

    @Value("${fileUpload.dirPath}")
    private String dirPath;

    @ApiOperation(value = "文件上传接口", httpMethod = "POST", notes = "将文件保存在当前服务器")
    @PostMapping("file")
    @ApiImplicitParams(@ApiImplicitParam(name = "idPic",value = "文件", required = true, type = "file"))
    public JSONResult fileUpload(HttpServletRequest request,
                                 @RequestParam("idPic") MultipartFile upload) throws IOException {
        String path = dirPath;
        path = fileUploadService.fileUploadInServer(upload, path);
        return JSONResult.ok(path);
    }

    @PostMapping("file2")
    public JSONResult fileUpload2(MultipartFile upload) throws IOException {
        String path = "http://localhost:9090/uploads/";
        //获取上传文件的名称
        String filename = upload.getOriginalFilename();
        //把文件的名称设置为唯一值,UUID
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + "_" + filename;
        //创建服务器对象
        Client client = Client.create();
        //和图片服务器连接
        WebResource webResource = client.resource(path + filename);
        //上传文件
        webResource.put(upload.getBytes());

        return JSONResult.ok(path+filename);
    }
}
